package com.wjzjq.hiring.company.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.wjzjq.hiring.common.PageModel;
import com.wjzjq.hiring.common.util.AppUtil;
import com.wjzjq.hiring.common.util.EmailUtils;
import com.wjzjq.hiring.company.dao.ApplicationDao;
import com.wjzjq.hiring.company.dao.CompanyDao;
import com.wjzjq.hiring.company.dao.PositionDao;
import com.wjzjq.hiring.company.entity.ApplicationEntity;
import com.wjzjq.hiring.company.entity.CompanyEntity;
import com.wjzjq.hiring.company.entity.PositionEntity;
import com.wjzjq.hiring.talent.dao.TalentDao;
import com.wjzjq.hiring.talent.entity.TalentEntity;

/**
 * Servlet implementation class CompanyServlet
 */
@WebServlet("/CompanyServlet")
public class CompanyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CompanyDao companyDao = new CompanyDao();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		String command = request.getParameter("command");
		if ("login".equals(command)) {
			login(request, response);
		} else if ("main".equals(command)) {
			main(request, response);
		} else if ("logout".equals(command)) {
			logout(request, response);
		} else if ("updateCompany".equals(command)) {
			this.updateCompany(request, response);
		}else if ("register".equals(command)) {
			register(request, response);
		} else if ("forgetPassword".equals(command)) {
			forgetPassword(request, response);
		} else if ("toResetPassword".equals(command)) {
			toResetPassword(request, response);
		} else if ("resetPassword".equals(command)) {
			resetPassword(request, response);
		}else if ("updatePassword".equals(command)) {
				this.updatePassword(request, response);
		}
	}
	
	private void resetPassword(HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		String code = request.getParameter("code");
		String newpassword = request.getParameter("newPassword");
		String repassword = request.getParameter("rePassword");
		if (newpassword.equals(repassword)) {
			if (companyDao.resetpwd(code, newpassword) != 0) {
				try {
					response.sendRedirect("PositionServlet?command=listAllPosition");
					return;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		try {
			request.setAttribute("error", "不得行");
			request.getRequestDispatcher("/view/company/resetPassword.jsp")
					.forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}

	private void toResetPassword(HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		String code = request.getParameter("code");
		request.setAttribute("code", code);
		try {
			request.getRequestDispatcher("/view/company/resetPassword.jsp")
					.forward(request, response);
		} catch (ServletException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void forgetPassword(HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		String email = request.getParameter("email");
		CompanyEntity company = companyDao.getCompanyByEmail(email);
		try {
			if (company == null) {
				request.setAttribute("error", "并没有这个邮箱");
				request.getRequestDispatcher("/view/company/forgetPassword.jsp")
						.forward(request, response);
				return;
			}
			EmailUtils.sendResetPasswordEmail(company);
			request.setAttribute("sendMailMsg",
					"您的申请已提交成功，请查看您的" + company.getEmail() + "邮箱。");
			request.getRequestDispatcher("/view/company/forgetPassword.jsp")
					.forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}

	private void logout(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		request.getSession().removeAttribute("company");
		try {
			response.sendRedirect(request.getContextPath() + "/index.jsp?logoutSuccess=true");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// FIXME
	private void register(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 接收参数
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		String phone = request.getParameter("phone");
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String linkman = request.getParameter("linkman");
		String address = request.getParameter("address");
		int numbers = Integer.valueOf(request.getParameter("numbers"));
		String slogan = request.getParameter("slogan");
		CompanyEntity company = new CompanyEntity();
		company.setCode(code);
		company.setEmail(email);
		company.setName(name);
		company.setPassword(password);
		company.setPhone(phone);
		company.setLinkman(linkman);
		company.setSlogan(slogan);
		company.setAddress(address);
		company.setNumbers(numbers);
		if (CompanyDao.register(company) != 0) {
			request.setAttribute("register", "注册成功请你登录");
			request.getRequestDispatcher("view/company/company-login.jsp?registerSuccess=true").forward(request, response);;// 注册成功去登陆页面
		} else {
			request.setAttribute("company", company);
			request.getRequestDispatcher("view/company/company-register.jsp?registerErr=true").forward(request,
					response);
		}

	}

	private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Object company = request.getSession().getAttribute("company");
		int pageNum = 1;
		int pageSum = 6;
		String pn = request.getParameter("pageNum");
		String ps = request.getParameter("pageSum");
		if (pn != null) {
			pageNum = Integer.valueOf(pn);
		}
		if (ps != null) {
			pageSum = Integer.valueOf(ps);
		}
		ApplicationEntity application = new ApplicationEntity();
		if (AppUtil.getCompanyId(request, response) != 0) {
			application.setCompanyId(AppUtil.getCompanyId(request, response));
		}
		application.setPositionName(request.getParameter("positionName"));
		String statusStr = request.getParameter("status");
		if (statusStr != null && !"".equals(statusStr)) {
			application.setStatus(Integer.valueOf(statusStr));
		}
		application.setStartTime(request.getParameter("startTime"));
		application.setEndTime(request.getParameter("endTime"));
		request.setAttribute("application", application);
		int companyId = ((CompanyEntity) company).getId();
		List<PositionEntity> positionList = CompanyDao.getPL(companyId);
		PageModel<PositionEntity> pageModelp = PositionDao.getAppListp(companyId,positionList, pageNum, pageSum);
		PageModel<ApplicationEntity> pageModel = ApplicationDao.getCompanyApp(application, pageNum, pageSum);
		request.setAttribute("pageModel", pageModel);
//		if (company != null) {
//			if (positionList != null && positionList.size() != 0){
				request.setAttribute("positionList", positionList);
				request.setAttribute("pageModelp", pageModelp);
//				}
//		}

		request.getRequestDispatcher("view/company/company-main.jsp").forward(request, response);
	}
	
	/**
	 * 修改密码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void updatePassword(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String oldpassword = request.getParameter("oldPassword");
		String newpassword = request.getParameter("newPassword");
		String repassword = request.getParameter("rePassword");
		System.out.println(newpassword);
		System.out.println(repassword);
		CompanyEntity companyE = (CompanyEntity) request.getSession()
				.getAttribute("company");
		String password = companyE.getPassword();

		if (oldpassword.equals(password)) {
			if (newpassword.equals(repassword)) {
				CompanyEntity company = new CompanyEntity();
				company.setPassword(repassword);
				company.setCode(companyE.getCode());
				company.setName(companyE.getName());
				company.setPhone(companyE.getPhone());
				company.setEmail(companyE.getEmail());
				company.setLinkman(companyE.getLinkman());
				company.setAddress(companyE.getAddress());
				company.setNumbers(companyE.getNumbers());
				company.setSlogan(companyE.getSlogan());
				company.setId(companyE.getId());
				int row = companyDao.update(company);
				if (row == 1) {
					System.out.println("success");
					request.getSession().setAttribute("company", company);
					response.sendRedirect(request.getContextPath()
							+ "/view/company/company-updatePassword.jsp?updateSuccess=true");
				} else {
					System.out.println("failed");
					response.sendRedirect(request.getContextPath()
							+ "/view/company/company-updatePassword.jsp?updateError=true");
				}
			} else {
				response.sendRedirect(request.getContextPath()
						+ "/view/company/company-updatePassword.jsp?repasswordError=true");
			}
		} else {
			response.sendRedirect(request.getContextPath()
					+ "/view/company/company-updatePassword.jsp?oldpasswordError=true");
		}
	}
	
	/**
	 * 更新个人资料
	 */

	private void updateCompany(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		// 从session里拿到id
		CompanyEntity companyE = (CompanyEntity) request.getSession().getAttribute("company");
		int id = companyE.getId();
		// 从页面上拿到更改的属性
		String password = request.getParameter("password");
		String phone = request.getParameter("phone");
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String linkman = request.getParameter("linkman");
		String address = request.getParameter("address");
		String slogan = request.getParameter("slogan");
		int numbers = Integer.valueOf(request.getParameter("numbers"));
		CompanyEntity company = new CompanyEntity();
		company.setEmail(email);
		company.setName(name);
		company.setPassword(password);
		company.setPhone(phone);
		company.setId(id);
		company.setLinkman(linkman);
		company.setAddress(address);
		company.setNumbers(numbers);
		company.setSlogan(slogan);
		company.setCode(companyE.getCode());
		int row = companyDao.update(company);
		if (row == 1) {
			// 若成功 要更新session 直接覆盖以前的属性
			company.setCode(companyE.getCode());
			request.getSession().setAttribute("company", company);
			response.sendRedirect(request.getContextPath() + "/view/company/company-info.jsp?updateSuccess=true");
		} else {
			response.sendRedirect(request.getContextPath() + "/view/company/company-info.jsp?updateError=true");
			System.out.println("failed");
		}

	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		// 1、接收参数
		String cCode = request.getParameter("code");
		String cPassword = request.getParameter("password");
		String cRemember = request.getParameter("remember");
		if ("true".equals(cRemember)) {
			// 创建cookie对象 并且避免中文乱码
			Cookie codeCookie = new Cookie("cCode", URLEncoder.encode(cCode, "utf-8"));
			// 如果没有设置存活时间，cookie在浏览器关闭时就会失效，也不会存入硬盘
			codeCookie.setMaxAge(60 * 30);
			// 在response里添加cookie 一共存三个 用户名 密码 和打勾
			response.addCookie(codeCookie);

			Cookie passwordCookie = new Cookie("cPassword", cPassword);
			passwordCookie.setMaxAge(60 * 30);
			response.addCookie(passwordCookie);

			Cookie rememberCookie = new Cookie("cRemember", cRemember);
			rememberCookie.setMaxAge(60 * 30);
			response.addCookie(rememberCookie);
		}
		CompanyEntity company = CompanyDao.login(cCode, cPassword);
		if (company != null) {
			request.getSession().setAttribute("company", company);
			request.getSession().removeAttribute("talent");
			// request.getRequestDispatcher("view/talent/main.jsp").forward(request,
			// response);
			response.sendRedirect("CompanyServlet?command=main");
		} else {
			// 登录失败
			response.sendRedirect("view/company/company-login.jsp?loginError=true");

		}
	}

}
